package client.command;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

import util.Command;
import util.Constant;
import util.Control;

public class Put extends Command {
	
	private OutputStream out;
	private InputStream in;
	private String pathFile;
	
	public Put(Socket socket,String pathFile) throws IOException{
		setSocket(socket);
		out = getSocket().getOutputStream();
		in = getSocket().getInputStream();
		this.pathFile = pathFile;
	}
	
	private void sendControlMessenger (Control msg) throws IOException{
		DataOutputStream data_out = new DataOutputStream(out);
		data_out.flush();
		data_out.writeInt(msg.Code());
	}
	/*
	 * protocolo para o Put:
	 * enviar: PUT
	 * Receber: RECEIVED
	 * --
	 * enviar: LINHA COM NOME DO ARQUIVO
	 * enviar: TAMANHO ARQUIVO
	 * enviar: ARQUIVO
	 * --
	 * RECEBER: SUCCESS
	 * 
	 */
	public void put(String pathFile){
		try {			
			DataInputStream data_in = new DataInputStream(in);
			  
			sendControlMessenger(Control.PUT);			
			
			if(data_in.readInt()!=Control.RECEIVED.Code()) throw new Exception("ERROR SINCRONIZACAO");
			
	        sendFile(pathFile);	        
	        
	        if(data_in.readInt()!=Control.SUCCESS.Code()) throw new Exception("ERROR AO TRANSMITIR ARQUIVO");
	     
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}		
	}
	
	private void sendFile(String pathFile) throws IOException{
		File file = new File(pathFile);  
        FileInputStream in = new FileInputStream(file);
        
        DataOutputStream data_out = new DataOutputStream(out);
		data_out.flush();
		
		System.out.println("Enviando arquivo: " + file.getName());
		data_out.writeUTF(file.getName());
		long size_file = file.length();
        data_out.writeLong(size_file);
        byte[] buffer = new byte[Constant.SIZE_BUFFER_CLIENT];    
        int bytes_read = -1;        
        
        while ((bytes_read = in.read(buffer, 0, Constant.SIZE_BUFFER_CLIENT)) != -1){
        	out.write(buffer, 0, bytes_read);
        }        
        in.close();
        System.out.println("Arquivo "+file.getName()+" enviado!");
	}
	
	public void execute() {
		put(pathFile);
	}
}
